import Vue from 'vue'
/**
 * 适用于元素拖动
 */
let isDown = false
let left,top = 0
function setElement(e,el){
  el.style.position = 'fixed'
  left = e.clientX - el.offsetLeft
  top = e.clientY - el.offsetTop
  el.style.top = e.clientY + top + 'px'
  el.style.left = e.clientX + left + 'px'
  window.addEventListener('mousemove',(e)=>dragElement(e,el))
  window.addEventListener('mouseup',(e)=>removeDrag(e,el))
  isDown = true
}
function dragElement(e,el){
  if (isDown){
    el.style.top = e.clientY - top + 'px'
    el.style.left = e.clientX - left + 'px'
  }
}
function removeDrag(e,el){
  isDown = false
  window.removeEventListener('mousemove',(e)=>dragElement(e,el))
  window.removeEventListener('mouseup',(e)=>removeDrag(e,el))
}
const drag ={
  install:function(){
    Vue.directive('drag',{
      inserted:function(el, binding, vnode, oldVnode){
        el.addEventListener('mousedown',(e)=>setElement(e,el))
      }
    })
  }
}
export default drag
